<template>
  <!-- 页面-拓展属性-编辑 -->
  <div class="addtmp innerPageTable-box-Four AddTemplate-page">
    <div class="addtmp-bar">
      <Form
        :label-width="90"
        :model="formData"
        :rules="ruleValidate"
        class="ivu-form-no-margin-bottom AddTemplate-Form"
        ref="addtempRef"
        inline
      >
        <template>
          <Row :gutter="32">
            <Col span="6">
              <!-- 模板类别 -->
              <Form-item
                prop="templateCategory"
                :label="$t('module.extend.templateCategory')"
                class="errorTip"
              >
                <Select
                  v-model="formData.templateCategory"
                  style="width: 200px;"
                  
                  :disabled="isEdit"
                  :placeholder="$t('module.extend.tip.templateCategory')"
                >
                  <Option
                    v-for="cate in temCategory"
                    :value="cate.vsiKey"
                    :key="cate.vsiKey"
                  >{{cate.vsiValue}}</Option>
                </Select>
              </Form-item>
            </Col>
            <Col span="6">
              <!-- 模板编码 -->
              <Form-item
                class="errorTip"
                prop="templateCode"
                :label="$t('module.extend.templateCode')"
              >
                <Input
                  :placeholder="$t('module.extend.tip.templateCode')"
                  :disabled="isEdit"
                  style="width: 200px;"
                  type="text"
                  v-model.trim="formData.templateCode"
                  
                />
              </Form-item>
            </Col>
            <Col span="6">
              <!-- 模板名称 -->
              <Form-item
                prop="templateName"
                :label="$t('module.extend.templateName')"
                class="errorTip"
              >
                <Input
                  :placeholder="$t('module.extend.tip.templateName')"
                  :disabled="formData.status === 2"
                  style="width: 200px;"
                  type="text"
                  :maxlength="30"
                  v-model="formData.templateName"
                  
                />
              </Form-item>
            </Col>
            <Col span="6">
              <!-- 模板版本 -->
              <Form-item prop="templateVersion" :label="$t('module.extend.templateVersion')">
                <Input
                  disabled
                  style="width: 200px;"
                  type="text"
                  :maxlength="30"
                  v-model="formData.templateVersion.toString()"
                  
                />
              </Form-item>
            </Col>
            <Col span="6">
              <!-- 模板状态 -->
              <Form-item prop="status" :label="$t('module.extend.status')">
                <Select disabled v-model="formData.status" style="width: 200px;" >
                  <Option
                    v-for="state in stateList"
                    :value="state.val"
                    :key="state.val"
                  >{{ state.name }}</Option>
                </Select>
              </Form-item>
            </Col>
          </Row>
        </template>
      </Form>
    </div>
    <div class="addtmp-tablebar">
      <Button
        :disabled="formData.status === 2 || !formData.templateCategory"
        @click="attrEditHandler()"
        
        type="primary"
      >
        {{
        $t("module.extend.addAttr")
        }}
      </Button>
      <Button @click="jsonModal = true" >JSON</Button>
    </div>
    <div class="addtmp-tmplist">
      <Table :columns="colomns" :data="attrList"></Table>
    </div>

    <div class="addtmp-action">
      <!-- <Icon type="md-bookmarks" /> -->
      <div></div>
      <div>
        <!-- 保存模板-按钮 -->
        <Button
          @click="saveValidHandler('add')"
          :disabled="formData.status === 2 || btnDisable"
          
          type="primary"
        >{{ $t("module.extend.saveTmp") }}</Button>
        <!-- <Button  type="warning" icon="ios-add">{{$t('module.extend.addAttr')}}</Button> -->
        <!-- 升级模板-按钮 -->
        <!-- <template v-if="isEdit && formData.status === 1">
          <Button
            :disabled="btnDisable"
            @click="saveValidHandler('upgrade')"
            
          >{{$t('module.extend.upTmp')}}</Button>
        </template>-->
        <!-- 发布模板 - 按钮 -->
        <template v-if="isEdit && formData.status === 0">
          <Button
            :disabled="btnDisable"
            @click="saveValidHandler('publish', formData)"
            
          >
            {{
            $t("module.extend.publish")
            }}
          </Button>
        </template>
      </div>
    </div>
    <Modal class="addtmp-model" width="650px" v-model="jsonModal">
      <p slot="header" class="zipkinmodal-header">
        <span>{{ $t("module.extend.JSONData") }}</span>
      </p>
      <pre class="addtmp-json"><code>{{attrList}}</code></pre>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>
<script>
import locales from "./locales.js";
import { addTmpColumns } from "./columns";
import addAttr from "./addAttr";
import { addTemplate, upgradeTemplate, publishTemplate } from "@/api/extendAttrApi";
import { codeReg } from "@/const.js";

export default {
  name: "AddTemplate",
  mixins: [locales],
  //   data: () => (),
  data() {
    var validateVsCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.extend.tip.templateCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };
    return {
      formData: {},
      attrList: [],
      isEdit: false,
      btnDisable: false,
      jsonModal: false,
      ruleValidate: {
        templateCategory: [
          { required: true, message: this.$t("module.extend.tip.templateCategory"), trigger: "change" }
        ],
        templateCode: [{ validator: validateVsCode, required: true, trigger: "blur" }],
        templateName: [{ required: true, message: this.$t("module.extend.tip.templateName"), trigger: "blur" }]
      },
      isChangeData: false
    };
  },
  props: {
    tmpData: {
      type: Object,
      default: () => ({})
    },
    temCategory: {
      type: Array,
      default: () => []
    },
    refresh: {
      type: Function,
      default: _ => _
    },
    isCopy: {
      type: Boolean,
      default: () => false
    },
  },
  computed: {
    stateList() {
      return [
        { name: this.$t("module.extend.draft"), val: 0 },
        { name: this.$t("module.extend.issue"), val: 1 },
        { name: this.$t("module.extend.pigeonhole"), val: 2 }
      ];
    },
    colomns() {
      return addTmpColumns.call(this);
    }
    // ruleValidate() {
    //   return {
    //     templateCategory: [
    //       { required: true, message: this.$t("module.extend.tip.templateCategory"), trigger: "change" }
    //     ],
    //     templateCode:[{ validator:this.validateVsCode,required: true,  trigger: "blur" }],
    //     templateName: [{ required: true, message: this.$t("module.extend.tip.templateName"), trigger: "blur" }]
    //   };
    // }
  },
  watch: {
    tmpData: {
      handler: function(val) {
        this.formData = { ...val };
        const _attr = val.attributeContent ? val.attributeContent.template || [] : [];
        this.attrList = _attr;
        this.isEdit = !!val.id;
      },
      immediate: true
    }
  },
  created () {
    const _this = this
    _this.$emit("SetCloseHook", () => {
      return new Promise((resolve, reject) => {
        if(_this.isCopy || _this.isChangeData) {
          _this.refresh();
        }
        resolve(true)
      })
    })
  },
  methods: {
    saveValidHandler(type, data) {
      this.$refs["addtempRef"].validate(valid => {
        if (valid) {
          this.saveHandler(type);
        } else {
          // this.$message.error(this.$t("common.formValidateFailed"));
        }
      });
    },
    async saveHandler(type) {
      const { formData, attrList } = this;
      formData.attributeContent = { template: attrList };
      try {
        this.btnDisable = true;
        let res;
        if (type === "add") {
          delete formData.duplicateFromId;
          // 类型为已发布且模板内容为空时给出提示
          if (attrList.length === 0 && formData.status == 1) {
            res = await new Promise((resolve, reject) => {
              this.$confirm.warning(this.$t("module.extend.tip.notEmpty")).then(
                () => {
                  addTemplate(formData).then(res => {
                    if (typeof res.data === "string") {
                      this.formData.id = res.data;
                      this.isEdit = true;
                      resolve();
                    } else {
                      resolve(res);
                    }
                  });
                },
                () => {
                  reject();
                }
              );
            });
          } else {
            const _res = await addTemplate(formData);
            if (typeof _res.data === "string") {
              this.formData.id = _res.data;
              this.isEdit = true;
            } else {
              res = _res;
            }
          }
          // 升级模板
        } else if (type === "upgrade") {
          res = await upgradeTemplate(formData);
        } else if (type === "publish") {
          // 确认信息
          let confirmContent = null;
          if (this.formData && this.formData.duplicateFromId) {
            // 已经发布过
            confirmContent = this.$t("module.extend.tipsContent");
          } else {
            // 未发布过
            if (attrList.length === 0) {
              // 没有属性
              confirmContent = this.$t("module.extend.tip.notEmpty");
            }
          }

          if (!!confirmContent) {
            res = await new Promise((resolve, reject) => {
              this.$confirm.warning(confirmContent).then(
                onOk => {
                  formData.status = 1;
                  delete formData.duplicateFromId;
                  publishTemplate(formData).then(res => {
                    res.data.status = 1;
                    resolve(res);
                  });
                },
                onCancel => {
                  reject();
                }
              );
            });
          } else {
            formData.status = 1;
            delete formData.duplicateFromId;
            res = await publishTemplate(formData);
            res.data.status = 1;
          }
        }

        if (res) {
          Object.assign(formData, res.data || {});
        }

        this.$message.success(this.$t("module.extend.success"));
        this.btnDisable = false;
        // this.refresh();
        this.isChangeData = true
      } catch (error) {
        this.btnDisable = false;
      }
    },
    // changeHandler(val) {
    //   this.formData.templateCode =
    //     val +
    //     Math.random()
    //       .toString()
    //       .slice(2);
    // },
    // 编辑和添加属性处理函数
    attrEditHandler(row) {
      const { attrList, formData: { templateCategory } } = this;
      const usedExtList = attrList.map(i => i.matchColumn) || [];
      const props = { rowData: row, fieldes: attrList.map(att => att.field), isEdit: this.isEdit, usedExtList, templateCategory };
      new this.$pageModal(addAttr, { props }, ({ result, isModify }) => {
        if (!result) return;
        // 是否是编辑
        if (isModify) {
          // for (const attr of attrList) {
          //   // 修改选项值
          //   if (attr.id === result.id) {
          //     Object.assign(attr, result);
          //     break;
          //   }
          // }
          for (let i = 0; i < attrList.length; i++) {
            // 修改选项值
            if (attrList[i].id === result.id) {
              // Object.assign(attr, result);
              attrList.splice(i, 1, result);
              break;
            }
          }
          return;
        }
        attrList.push(result);
      });
    },
    // 删除属性处理函数
    attrDeleteHandler(row) {
      this.$confirm.warning(this.$t("common.warning.confirmToDelete")).then(() => {
        this.attrList = this.attrList.filter(r => !(row.field === r.field));
      });
      // this.$Modal.confirm({
      //   title: this.$t("common.warning.confirmToDelete"),
      //   content: "确定删除?",
      //   onOk: () => {
      //     this.attrList = this.attrList.filter(r => !(row.field === r.field));
      //   }
      // });
    }
  }
};
</script>
<style lang="less" scoped>
.addtmp {
  box-sizing: border-box;
  padding: 0 10px;
}
.addtmp-bar {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.addtmp-action {
  margin-top: 10px;
  /* padding-right: 10px; */
  display: flex;
  justify-content: space-between;
}
.addtmp-action button {
  font-size: 14px;
  height: 34px;
  padding: 3px 23px;
  border-radius: 0px;
  margin-right: 18px;
}
.json-style {
  border: 1px solid #ed4014;
  border-radius: 4px;
}
.addtmp-tablebar {
  margin-bottom: 10px;
  border-top: 1px solid #f1f1f1;
  padding-top: 10px;
  button {
    font-size: 14px;
    height: 34px;
    padding: 3px 23px;
    border-radius: 0px;
    margin-right: 18px;
  }
  // 第一个按钮样式
  // button:first-child {
  //   color: #fff;
  //   background-color: #ff6f4b;
  //   border-color: #ff6f4b;
  // }
  // // 后续按钮样式
  // :not(:first-child) {
  //   color: #ff6f4b;
  //   background-color: #ffffff;
  //   border-color: #ff6f4b;
  // }
}
.addtmp-json {
  background-color: #333;
  color: #fff;
  box-sizing: border-box;
  padding: 10px;
}
.addtmp-tmplist {
  max-height: 520px;
  overflow-y: hidden;
}
</style>
<style lang="less">
.addtmp-model .ivu-modal-body {
  background-color: #333;
  max-height: 460px;
  overflow-y: scroll;
}
// ok注释的样式
.AddTemplate-page {
  .ivu-form {
    .ivu-row {
      .ivu-col {
        .ivu-form-item {
          .ivu-form-item-label {
            width: 68px !important;
            padding: 10px 0 !important;
            line-height: 14px !important;
          }
          .ivu-form-item-content {
            margin-left: 0px !important;
            padding-left: 14px !important;
          }
        }
      }
    }
  }
}
</style>
<style lang="less">
.AddTemplate-page {
  .AddTemplate-Form {
    .ivu-col {
      .ivu-form-item {
        margin-top: 28px !important;
      }
      .errorTip {
        .ivu-form-item-error-tip {
          position: absolute !important;
          left: 14px;
          white-space: nowrap;
        }
      }
    }
  }
}
</style>
